package jinyilw.swing.visuals.Jcomp;

import jinyilw.common.Operator;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class JImageComp extends JMouseActComp
{
	private static final long serialVersionUID = -1276675463020135887L;
	protected Image image;

	public JImageComp()
	{
	}

	public JImageComp(Image img)
	{
		image = img;
	}

	public void setImage(Image img)
	{
		if (image != img)
		{
			image = img;
			if (isShowing())
				repaint();
		}
	}

	public Image getImage()
	{
		return image;
	}

	public boolean isBlank()
	{
		return image == null;
	}

	public void addDoubleClickOperator(final Operator<MouseEvent> operator)
	{
		addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				if (isEnabled() && e.getClickCount() == 2)
					operator.operate(e);
			}
		});
	}

	@Override
	protected void paintComponent(Graphics g)
	{
		if (image != null)
		{
			Insets insets = getInsets();
			int width = getWidth() - insets.left - insets.right;
			int height = getHeight() - insets.top - insets.bottom;
			g.drawImage(image, insets.left, insets.top, width, height, null);
		}
	}

	public void clearImage()
	{
		image = null;
		if (isShowing())
			repaint();
	}
}
